import { initParticlesJS } from '../particles.js';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 初始化粒子效果
    initParticlesJS();
    // 检查用户登录状态并更新界面
    updateUserInterface();

    // 从 URL 中获取参数
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }

    const postId = getUrlParameter('id');

    // 打印参数到控制台
    console.log('帖子 ID:', postId);

    if (postId) {
        loadPostDetails(postId);
    } else {
        alert('帖子 ID 不存在');
    }

    // 加载推荐帖子
    loadRecommendedPosts();

    // 设置交互功能
    setupInteractions();

    // 设置正在开发中的功能
    setupDevelopmentFeatures();

    // 移动菜单切换
    document.getElementById('mobile-menu-btn').addEventListener('click', function () {
        const mobileMenu = document.getElementById('mobile-menu');
        if (mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.remove('hidden');
        } else {
            mobileMenu.classList.add('hidden');
        }
    });

    // 更新购物车数量
    updateCartCount();
});

// 更新用户界面
function updateUserInterface() {
    const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
    const authSection = document.getElementById('user-auth-section');
    const infoSection = document.getElementById('user-info-section');
    const needLoginMessage = document.getElementById('need-login-message');
    const commentFormContainer = document.getElementById('comment-form-container');

    if (user) {
        authSection.classList.add('hidden');
        infoSection.classList.remove('hidden');
        document.getElementById('username').textContent = user.username;
        document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';

        needLoginMessage.classList.add('hidden');
        commentFormContainer.classList.remove('hidden');

        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', function () {
            localStorage.removeItem('currentUser');
            window.location.reload();
        });
    } else {
        authSection.classList.remove('hidden');
        infoSection.classList.add('hidden');

        needLoginMessage.classList.remove('hidden');
        commentFormContainer.classList.add('hidden');
    }
}

// 更新购物车数量
function updateCartCount() {
    const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
    const cartCount = document.getElementById('cart-count');
    cartCount.textContent = cart.length;
}

// 加载帖子详情
function loadPostDetails(postId) {
    // 发送 AJAX 请求获取帖子详情
    fetch(`http://localhost:3000/api/getPostsByPostId?postId=${postId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 && data.data.length > 0) {
                const post = data.data[0];

                // 更新页面标题
                document.title = `${post.title} - 钓鱼论坛`;

                // 更新帖子内容
                document.getElementById('post-title').textContent = post.title;
                document.getElementById('post-title-breadcrumb').textContent = post.title;
                document.getElementById('post-section').textContent = post.plate.plateName;
                document.getElementById('post-section-breadcrumb').textContent = post.plate.plateName;
                document.getElementById('post-date').innerHTML = `<i class="far fa-calendar mr-1"></i>${formatDate(post.createTime)}`;
                document.getElementById('post-views').innerHTML = `<i class="far fa-eye mr-1"></i>${post.views || 0} 浏览`;
                document.getElementById('post-comments-count').innerHTML = `<i class="far fa-comment mr-1"></i>${post.commentCount || 0} 评论`;
                document.getElementById('comment-count').textContent = `(${post.commentCount || 0})`;
                document.getElementById('post-author').textContent = post.user.nickname;
                document.getElementById('post-author-avatar').src = post.user.avatar || `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`;
                document.getElementById('post-likes-count').textContent = post.likeCount || 0;

                // 设置帖子内容
                document.getElementById('post-content').innerHTML = post.content;

                // 设置分享链接
                document.getElementById('share-link').value = window.location.href;

                // 更新评论
                updateComments(post);

                // 模拟增加浏览量
                incrementViewCount(postId);
            } else {
                // window.location.href = 'forum.html';
            }
        })
        .catch(error => {
            console.error('获取帖子详情失败:', error);
        });
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
}

// 更新评论列表
function updateComments(post) {
    const commentsContainer = document.getElementById('comments-list');
    commentsContainer.innerHTML = '';

    if (!post.comments || post.comments.length === 0) {
        commentsContainer.innerHTML = `
            <div class="p-6 text-center text-gray-500">
                <i class="far fa-comment-dots text-4xl mb-2"></i>
                <p>暂无评论，来发表第一条评论吧！</p>
            </div>
        `;
        return;
    }

    post.comments.forEach((comment, index) => {
        const commentElement = document.createElement('div');
        commentElement.className = 'p-6';
        commentElement.innerHTML = `
            <div class="flex">
                <div class="flex-shrink-0 mr-4">
                    <img src="${comment.userAvatar || `https://picsum.photos/id/${50 + index}/200/200`}" alt="${comment.userNickname}" class="w-10 h-10 rounded-full">
                </div>
                <div class="flex-1">
                    <div class="flex items-center mb-1">
                        <h4 class="font-medium mr-2">${comment.userNickname}</h4>
                        <span class="text-xs text-gray-500">${formatDate(comment.commentTime)}</span>
                        <span class="text-xs text-gray-500 ml-auto">#${index + 1}</span>
                    </div>
                    <div class="text-gray-800 mb-3">${comment.content}</div>
                    <div class="flex items-center text-sm text-gray-500">
                        <button class="comment-like-btn mr-4 hover:text-blue-600 transition" data-comment-id="${comment.commentId}">
                            <i class="far fa-thumbs-up mr-1"></i>
                            <span>${comment.likes || 0}</span>
                        </button>
                        <button class="comment-reply-btn hover:text-blue-600 transition" data-comment-id="${comment.commentId}">
                            <i class="far fa-comment mr-1"></i>回复
                        </button>
                    </div>
                </div>
            </div>
        `;
        commentsContainer.appendChild(commentElement);
    });

    // 添加评论点赞功能
    const likeButtons = document.querySelectorAll('.comment-like-btn');
    likeButtons.forEach(button => {
        button.addEventListener('click', function () {
            const commentId = this.getAttribute('data-comment-id');
            const likeCountElement = this.querySelector('span');
            let likeCount = parseInt(likeCountElement.textContent);
            likeCount += 1;
            likeCountElement.textContent = likeCount;

            // 更新评论点赞数
            updateCommentLikes(post.postId, commentId, likeCount);

            // 显示点赞动画
            const icon = this.querySelector('i');
            icon.classList.remove('far');
            icon.classList.add('fas', 'text-blue-600');

            // 显示通知
            showNotification('点赞成功！');
        });
    });

    // 添加评论回复功能
    const replyButtons = document.querySelectorAll('.comment-reply-btn');
    replyButtons.forEach(button => {
        button.addEventListener('click', function () {
            const commentId = this.getAttribute('data-comment-id');
            const comment = post.comments.find(c => c.commentId === commentId);

            if (comment) {
                const textarea = document.getElementById('comment-content');
                textarea.value = `@${comment.userNickname} `;
                textarea.focus();

                // 滚动到评论表单
                document.getElementById('comment-form').scrollIntoView({ behavior: 'smooth' });
            }
        });
    });
}

// 加载推荐帖子
function loadRecommendedPosts() {
    const container = document.getElementById('recommended-posts');

    // 从localStorage获取所有帖子
    const storedPosts = localStorage.getItem('forumPosts');
    let allPosts = [];

    if (storedPosts) {
        allPosts = JSON.parse(storedPosts);
    }

    // 获取当前帖子ID
    const urlParams = new URLSearchParams(window.location.search);
    const currentPostId = urlParams.get('id');

    // 过滤掉当前帖子，并随机选择最多3个帖子
    const filteredPosts = allPosts.filter(post => post.id !== currentPostId);
    const recommendedPosts = filteredPosts.sort(() => 0.5 - Math.random()).slice(0, 3);

    // 清空容器
    container.innerHTML = '';

    if (recommendedPosts.length === 0) {
        // 如果没有其他帖子，显示一些模拟数据
        const dummyPosts = [
            {
                id: "101",
                title: "夏季钓鱼的最佳时间",
                author: "四季钓手",
                date: "2025-04-28",
                section: "钓技研究",
                views: 122
            },
            {
                id: "102",
                title: "自制鲫鱼饵料配方分享",
                author: "饵料专家",
                date: "2025-04-30",
                section: "淡水钓鱼",
                views: 145
            },
            {
                id: "103",
                title: "新手必读：钓具选购指南",
                author: "渔具店老板",
                date: "2025-05-02",
                section: "装备讨论",
                views: 198
            }
        ];

        dummyPosts.forEach(post => {
            createRecommendedPostCard(post, container);
        });
    } else {
        // 创建推荐帖子卡片
        recommendedPosts.forEach(post => {
            createRecommendedPostCard(post, container);
        });
    }
}

// 创建推荐帖子卡片
function createRecommendedPostCard(post, container) {
    const postCard = document.createElement('div');
    postCard.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition duration-300';
    postCard.innerHTML = `
        <a href="post.html?id=${post.id}" class="block">
            <div class="p-5">
                <h3 class="font-bold text-lg mb-2 line-clamp-2 hover:text-blue-600 transition">${post.title}</h3>
                <div class="flex justify-between text-sm text-gray-500">
                    <span><i class="fas fa-user mr-1"></i>${post.author}</span>
                    <span><i class="fas fa-tag mr-1"></i>${post.section}</span>
                </div>
            </div>
        </a>
    `;
    container.appendChild(postCard);
}

// 更新评论点赞数
function updateCommentLikes(postId, commentId, newLikeCount) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);

    if (postIndex !== -1) {
        const post = posts[postIndex];
        const commentIndex = post.comments.findIndex(c => c.id === commentId);

        if (commentIndex !== -1) {
            post.comments[commentIndex].likes = newLikeCount;
            localStorage.setItem('forumPosts', JSON.stringify(posts));
        }
    }
}

// 增加浏览量
function incrementViewCount(postId) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);

    if (postIndex !== -1) {
        const post = posts[postIndex];
        post.views = (post.views || 0) + 1;
        localStorage.setItem('forumPosts', JSON.stringify(posts));

        // 更新显示
        document.getElementById('post-views').innerHTML = `<i class="far fa-eye mr-1"></i>${post.views} 浏览`;
    }
}

// 设置交互功能
function setupInteractions() {
    // 获取当前帖子ID
    const urlParams = new URLSearchParams(window.location.search);
    const postId = urlParams.get('id');

    // 帖子点赞
    const likePostBtn = document.getElementById('like-post-btn');
    likePostBtn.addEventListener('click', function () {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;

        if (!user) {
            showNotification('请先登录后再点赞！');
            return;
        }

        const likeCountElement = document.getElementById('post-likes-count');
        let likeCount = parseInt(likeCountElement.textContent);
        likeCount += 1;
        likeCountElement.textContent = likeCount;

        // 更新帖子点赞数
        updatePostLikes(postId, likeCount);

        // 改变按钮样式
        const icon = this.querySelector('i');
        icon.classList.remove('far');
        icon.classList.add('fas', 'text-blue-600');

        // 显示通知
        showNotification('点赞成功！');
    });

    // 收藏帖子
    const collectPostBtn = document.getElementById('collect-post-btn');
    collectPostBtn.addEventListener('click', function () {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;

        if (!user) {
            showNotification('请先登录后再收藏！');
            return;
        }

        // 改变按钮样式
        const icon = this.querySelector('i');
        if (icon.classList.contains('far')) {
            icon.classList.remove('far');
            icon.classList.add('fas', 'text-yellow-500');
            showNotification('帖子已收藏！');
        } else {
            icon.classList.remove('fas', 'text-yellow-500');
            icon.classList.add('far');
            showNotification('已取消收藏！');
        }
    });

    // 分享帖子
    const sharePostBtn = document.getElementById('share-post-btn');
    const shareModal = document.getElementById('share-modal');
    const closeShareModal = document.getElementById('close-share-modal');
    const copyLink = document.getElementById('copy-link');

    sharePostBtn.addEventListener('click', function () {
        shareModal.classList.remove('hidden');
    });

    closeShareModal.addEventListener('click', function () {
        shareModal.classList.add('hidden');
    });

    copyLink.addEventListener('click', function () {
        const shareLink = document.getElementById('share-link');
        shareLink.select();
        document.execCommand('copy');
        showNotification('链接已复制到剪贴板！');
    });

    // 举报帖子
    const reportPostBtn = document.getElementById('report-post-btn');
    const reportModal = document.getElementById('report-modal');
    const closeReportModal = document.getElementById('close-report-modal');
    const cancelReport = document.getElementById('cancel-report');
    const submitReport = document.getElementById('submit-report');
    const reasonRadios = document.querySelectorAll('input[name="report-reason"]');
    const otherReasonContainer = document.getElementById('other-reason-container');

    reportPostBtn.addEventListener('click', function () {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;

        if (!user) {
            showNotification('请先登录后再举报！');
            return;
        }

        reportModal.classList.remove('hidden');
    });

    closeReportModal.addEventListener('click', function () {
        reportModal.classList.add('hidden');
    });

    cancelReport.addEventListener('click', function () {
        reportModal.classList.add('hidden');
    });

    reasonRadios.forEach(radio => {
        radio.addEventListener('change', function () {
            if (this.value === 'other') {
                otherReasonContainer.classList.remove('hidden');
            } else {
                otherReasonContainer.classList.add('hidden');
            }
        });
    });

    submitReport.addEventListener('click', function () {
        // 获取选中的原因
        const selectedReason = document.querySelector('input[name="report-reason"]:checked');

        if (!selectedReason) {
            showNotification('请选择举报原因！', 'red');
            return;
        }

        let reason = selectedReason.value;

        if (reason === 'other') {
            const otherReason = document.getElementById('other-reason').value.trim();
            if (!otherReason) {
                showNotification('请说明举报原因！', 'red');
                return;
            }
            reason = otherReason;
        }

        // 关闭模态框
        reportModal.classList.add('hidden');

        // 显示通知
        showNotification('举报已提交，感谢您的反馈！');
    });

    // 提交评论
    const submitCommentBtn = document.getElementById('submit-comment');
    submitCommentBtn.addEventListener('click', function () {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;

        if (!user) {
            showNotification('请先登录后再发表评论！');
            return;
        }

        const commentContent = document.getElementById('comment-content').value.trim();
        const commentError = document.getElementById('comment-error');

        if (!commentContent) {
            commentError.classList.remove('hidden');
            return;
        } else {
            commentError.classList.add('hidden');
        }

        // 添加新评论
        addNewComment(postId, user, commentContent);

        // 清空评论框
        document.getElementById('comment-content').value = '';

        // 显示通知
        showNotification('评论发布成功！');
    });
}

// 更新帖子点赞数
function updatePostLikes(postId, newLikeCount) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);

    if (postIndex !== -1) {
        posts[postIndex].likes = newLikeCount;
        localStorage.setItem('forumPosts', JSON.stringify(posts));
    }
}

// 添加新评论
function addNewComment(postId, user, content) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);

    if (postIndex !== -1) {
        const post = posts[postIndex];

        // 如果没有评论数组，创建一个
        if (!post.comments) {
            post.comments = [];
        }

        // 创建新评论
        const newComment = {
            id: 'c' + Date.now(),
            author: user.username,
            authorAvatar: user.avatar,
            content: content,
            date: new Date().toISOString(),
            likes: 0
        };

        // 添加到评论列表
        post.comments.push(newComment);

        // 保存到localStorage
        localStorage.setItem('forumPosts', JSON.stringify(posts));

        // 重新加载评论
        updateComments(post);

        // 更新评论数显示
        document.getElementById('post-comments-count').innerHTML = `<i class="far fa-comment mr-1"></i>${post.comments.length} 评论`;
        document.getElementById('comment-count').textContent = `(${post.comments.length})`;
    }
}

// 设置正在开发中的功能
function setupDevelopmentFeatures() {
    const devFeatureButtons = [
        document.getElementById('communityBtn'),
        document.getElementById('techniqueBtn')
    ];

    const devModal = document.getElementById('development-modal');
    const closeDevModal = document.getElementById('close-dev-modal');

    devFeatureButtons.forEach(button => {
        if (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                devModal.classList.remove('hidden');
            });
        }
    });

    closeDevModal.addEventListener('click', function () {
        devModal.classList.add('hidden');
    });
}

// 显示通知
function showNotification(message, color = 'green') {
    const notification = document.getElementById('notification');
    notification.textContent = message;

    if (color === 'red') {
        notification.classList.remove('bg-green-500');
        notification.classList.add('bg-red-500');
    } else {
        notification.classList.remove('bg-red-500');
        notification.classList.add('bg-green-500');
    }

    notification.classList.remove('hidden');
    notification.classList.remove('translate-y-20', 'opacity-0');

    setTimeout(() => {
        notification.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }, 2000);
}